package com.zhongli.devplatform.security.weixin;

import com.alibaba.fastjson.JSON;
import com.zhongli.devplatform.po.sys.ReadUserLoginPO;
import com.zhongli.devplatform.service.imp.sys.ReadUserLoginService;
import com.zhongli.devplatform.service.imp.sys.ReadSystemParameterService;
import com.zhongli.devplatform.utils.CusAccessObjectUtil;
import com.zhongli.devplatform.component.SpringUtil;
import com.zhongli.devplatform.bean.Res;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Slf4j
public class WeixinAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        ReadUserLoginPO userLoginPO = new ReadUserLoginPO();

        log.error("微信绑定失败：" + exception.getMessage());

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        userLoginPO.setLoginBrowser(userAgent.getBrowser().getName());
        userLoginPO.setLoginIp(CusAccessObjectUtil.getIpAddress(request));
        userLoginPO.setLoginRemark("微信登陆失败，该用户未绑定微信");
        userLoginPO.setLoginStatus("0");
        userLoginPO.setLoginType("2");
        userLoginPO.setLoginUa(request.getHeader("User-Agent"));
        userLoginPO.setLoginTime(new Date());
        SpringUtil.getBean(ReadUserLoginService.class).save(userLoginPO);


        ReadSystemParameterService systemParameterService = SpringUtil.getBean(ReadSystemParameterService.class);


        String weixin_login_error_type = systemParameterService.getSystemParameter("weixin_login_error_type");


        if ("redirect".equals(weixin_login_error_type)) {
            String weixin_login_error_url = systemParameterService.getSystemParameter("weixin_login_error_url");
            response.sendRedirect(weixin_login_error_url + "?weixinId=" + request.getAttribute("weixinId"));
        } else {
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(new Res(request.getAttribute("weixinId"))));
            out.flush();
            out.close();
        }


    }
}
